package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.UploadObjectArgs;
import lombok.SneakyThrows;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    MinioProperties minioProperties;

    @SneakyThrows
    @Override
    public String upload(MultipartFile file) {
        InputStream inputStream = file.getInputStream();// 图片的流

        // 客户端
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
//                .endpoint("http://192.168.109.130:9000") // 这是代码写死的用法，改成配置文件
//                .credentials("minioadmin", "minioadmin") // 这是代码写死的用法，改成配置文件
                .build();


        // 文件和路径和后缀
        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        String uuname = UUID.randomUUID().toString().replace("-", "");
        String dateStr = new DateTime().toString("yyyy/MM/dd/");
        String fileName = dateStr + uuname + "." + filenameExtension;


        // 参数
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .stream(inputStream, file.getSize(), -1)
//                .bucket("lease-0715")
                .bucket(minioProperties.getBucketName())    // bucket
                .object(fileName)// 日期文件夹路径+UUID文件名+后缀
                .build();

        // 上传
        minioClient.putObject(putObjectArgs);

//        return "http://192.168.109.130:9000/" + "lease-0715/" + fileName;
        return minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName;
    }
}